#coding=utf-8

from db_manager import DBManager 
from  config import *
from tool import Tool
import datetime
import time
import json

class Merchant(object):
    def __init__(self,cfgParam):
        self.cfgParam = cfgParam
        self.manager = DBManager(db,ip,ur,pd)
        self.manager.connect()
        self.tool = Tool()
    def merchant_allincome(self):
        """ 查询商户总收益方法 """
        merchantid = int(self.cfgParam["merchantid"])
        execsql = "select a.datetime,sum(a.all_income) as all_income from %s as a left join store_info as b on a.storeid = b.storeid   where b.merchantid =%d group by a.datetime" %(store_report,merchantid)
        result = self.manager.query(execsql)
        resultdic = {}
        for row in result:
            date = (row["datetime"])
            year,month,day = str(date.year),str(date.month),str(date.day)
            if year not in resultdic:
                resultdic[year] ={}
            if month not in resultdic[year]:
                resultdic[year][month] = {}
            if day not in resultdic[year][month]:
                resultdic[year][month][day] = {}
            resultdic[year][month][day]["all_income"] = row["all_income"]
            resultdic[year][month][day]["store"] = {}
        return resultdic

    def query_merchant_income(self):
        """ 商户总收益以及每家门店每日收益 """

        mustkeys = ["merchantid"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        merchantid = int(self.cfgParam["merchantid"])
        execsql = " select a.*,b.storename  from %s as a left join %s as b on a.storeid = b.storeid where b.merchantid= %d " %(store_report,store_info,merchantid)
        result = self.manager.query(execsql)
        retdic = self.merchant_allincome()
        for row in result:
            date = row["datetime"]
            year,month,day = str(date.year),str(date.month),str(date.day)
            retdic[year][month][day]["store"][row["storeid"]]= {
                "storeid"  :row["storeid"],
                "storename":row["storename"],
                "income":row["all_income"]
            }
        ret["status"] = 1
        ret["result"] = retdic
        return ret 

    def query_machine_income(self):
        "查询店面里机器每天的流水 显示最近收入信息"
        mustkeys = ["storeid"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        storeid = int(self.cfgParam["storeid"])
        execsql = "select    a.* from %s  as a inner join  (select mid from %s  where storeid = %d ) as b on a.mid  = b.mid  "%(user_consume,machine_relation,storeid)
        result = list(self.manager.query(execsql))
        ret["status"] = result       
        return ret

    def query_store_info(self):
        "查询商户所有门店以及未分组机器总数"
        mustkeys = ["merchantid"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        try:
            merchantid = int(self.cfgParam["merchantid"])
            data = {'nongroup':[],'group':[]}
            execsql = "SELECT count(mid) as count,a.storeid,b.storename,b.is_defaultgroup FROM machine_relation  as a  left join store_info as b on a.storeid = b.storeid   where a.merchantid =%d and b.store_status = 1 GROUP BY  a.storeid     " %merchantid 
            result = self.manager.query(execsql)
            for row in result:
                 if row["is_defaultgroup"]:
                     data['nongroup'].append(row)
                 else :
                     data['group'].append(row)                
               
        except Exception,e:
            print e            
        return data
    def query_machine_info(self):
        """ 查询 商户下所有未分组和已分组门店 下的机器信息"""
        mustkeys = ["merchantid"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        merchantid = int(self.cfgParam["merchantid"])
        retdic ={"group":[],"nongroup":[]}
	#当前时间
        updatetime = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
        updatedate = updatetime.split(" ")[0]
	#查询商户所有门店
        qry_storeid_sql = "SELECT * from %s  where merchantid = %d and store_status = 1 " %(store_info,merchantid)
        result  = list(self.manager.query(qry_storeid_sql))
        for row in result:
	    storeid = row["storeid"]
	    row["start_time"] = str(row["start_time"])
	    row["end_time"] = str(row["end_time"])
	    qry_machine_sql = "select a.* from %s as a inner join %s as b on a.MachineId = b.mid  where b.storeid = %d and a.STATUS=1 "%(machine_info,machine_relation,storeid)
	    qry_machine_result = self.manager.query(qry_machine_sql)
	    #统计设备总收入，今日收入 
            for index,machine in enumerate(qry_machine_result):
	        mid = machine["MachineId"]
		print mid
                qry = "select all_income  from {0} where mid = {1} and datetime = '{2}'".format(machine_report,mid,updatedate)
		result = self.manager.query(qry)
		if result :
		    mid_todayincome = result[0]["all_income"]
		else:
		    mid_todayincome = 0
		qry_machine_result[index]["mid_todayincome"] = mid_todayincome
	    row["machine_detail"] = qry_machine_result
	    if row["is_defaultgroup"] == 1 and retdic["nongroup"] == []:
	        retdic["nongroup"] = row
	    elif row["is_defaultgroup"] == 0:
	        retdic["group"].append(row)
        ret["result"] = retdic
        return ret

    def update_merchant_detail(self):
        mustkeys = ["merchantid","detail"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        merchant_detail = json.loads(self.cfgParam["detail"])
	condition = {"merchantid":int(self.cfgParam["merchantid"])}
        self.manager.smartUpdate(merchant_info,merchant_detail,condition)
        ret["status"] = 1
        return ret

if __name__ == "__main__":
    cfgParam = {'cmd':"1"}
    m=Merchant(cfgParam)
    print m.query1()
    
